<template >
    <div>

        <el-dialog v-model="arr.isShow" :title="arr.isAdd ? '角色添加' : '角色编辑'" width="30%" :before-close="handleClose"
            center>
            <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="角色名称" prop="rolename">
                    <el-input v-model="form.rolename" />
                </el-form-item>
                <el-form-item label="角色权限">
                    <el-tree ref="js" @check="currentChecked" default-expand-all :data="menulist" show-checkbox
                        node-key="id" :props="{
                            children: 'children',
                            label: 'title',
                        }" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.status" class="ml-2" :active-value="1" :inactive-value="2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="affrim(ruleFormRef)">确定</el-button>
                </span>
            </template>

        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, computed, defineExpose } from 'vue'
import { ElMessage, FormRules } from 'element-plus'
// import type Node from 'element-plus/es/components/tree/src/model/node'
import { roleadd, roleinfo, roleedit } from '../../request/api'
import type { FormInstance } from 'element-plus'
import { useStore } from 'vuex'
const getMenus = () => {
    store.dispatch("role/getRoleAction");
};


let js = ref()
let newId = 0;
let lookup = (e: any) => {
    newId = e
    roleinfo({ id: e }).then((res:any) => {
        console.log(res);

        if (res.code == 200) {
            form.value = res.list
            js.value.setCheckedKeys(
                form.value.menus ? form.value.menus.split(',') : []
            )

        }
    })
}
defineExpose({ lookup })
let currentChecked = (nodeObj: any, SelectedObj: any) => {
    //   console.log(nodeObj.checkedKeys)   
    console.log(SelectedObj.checkedKeys)   // 这是选中的节点的key数组
    console.log(SelectedObj.checkedNodes)
    jd.value = SelectedObj// 这是选中的节点数组  
}

let jd = ref()
const store = useStore()
const menulist = computed(() => store.getters["menu/getMenu"]);
const getMenu = () => {
    store.dispatch("menu/getMenuAction");
};
console.log(menulist);

getMenu()
const ruleFormRef = ref<FormInstance>()
let emit = defineEmits(['cancel'])
const cancel = (formEl: FormInstance | undefined) => {
    emit('cancel')
    js.value.setCheckedKeys([])
    if (!formEl) return
    formEl.resetFields()
}
let affrim = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (arr.isAdd) {
                // 添加
                form.value.menus = jd.value.checkedKeys.join(',')
                //   console.log(jd.value,'222');
                // console.log(form.value);
                roleadd(form.value).then(res => {
                    // console.log(res,'tianjia');
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            grouping: true,
                            type: 'success',
                        })
                        cancel(formEl)
                        getMenus();
                    } else {
                        ElMessage({
                            message: res.msg,
                            grouping: true,
                            type: 'error',
                        })
                    }

                })

            } else {
                // 编辑
                form.value.menus = jd.value.checkedKeys.join(',')
                roleedit({ ...form.value, id: newId }).then((res: any) => {
                    // console.log(res,'355');
                    if (res.code == 200) {
                        ElMessage.success(res.msg)
                        cancel(formEl)
                        getMenus()
                    } else {
                        ElMessage.error(res.msg)
                    }

                })
            }
            // console.log('submit!')
        } else {
            // console.log('error submit!', fields)
            console.log('验证失败');
            // console.log(props.isAdd);

        }
    })
}
let arr = defineProps({
    isShow: Boolean,
    isAdd: Boolean,

})

const handleClose = (done: () => void) => {
    done()
    cancel(ruleFormRef.value);
}
let form = ref({
    rolename: '',
    menus: '',
    status: 1
})
const rules = reactive<FormRules>({
    rolename: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 5, message: '名称为2到5位', trigger: 'blur' },
    ]
})

</script>
<style >
</style>